/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * EmployeeInsuranceEditor.java
 *
 * Created on Mar 20, 2010, 6:24:14 PM
 */

package org.foment.gem.beans;
import java.beans.PropertyChangeEvent;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.xml.crypto.dsig.keyinfo.KeyValue;
import org.foment.joliage3.core.logging.Logger;
import org.foment.joliage3.sql.Database;
import static org.foment.joliage3.core.internationalization.Internationalization.i18n;
import static org.foment.joliage3.core.logging.Logger.log;
import org.foment.joliage3.core.logging.Logger.*;
import org.foment.joliage3.newt.*;
import org.foment.joliage3.sql.Table.TableEditor;
import org.foment.gem.Integrator;
import org.foment.data.User;


/**
 *
 * @author Dusan
 */
public class EmployeeInsuranceEditor extends javax.swing.JPanel implements java.io.Serializable, TableEditor, User.UserListener{

    /** Creates new form EmployeeInsuranceEditor */
    public EmployeeInsuranceEditor() {
        
        initComponents();

        Integrator._user.addListener(this);
        checkPrivileges();

        flg2_EmployeeInsuranceGender.getDocument().addDocumentListener(
        new javax.swing.event.DocumentListener() {
          public void changedUpdate(DocumentEvent documentEvent) { updated(documentEvent); }
          public void insertUpdate(DocumentEvent documentEvent)  { updated(documentEvent); }
          public void removeUpdate(DocumentEvent documentEvent)  { updated(documentEvent); }
          public void updated(DocumentEvent documentEvent) {
            if (flg2_EmployeeInsuranceGender.getText().equals("m"))         radioMale.setSelected(true);
            else if (flg2_EmployeeInsuranceGender.getText().equals("f"))    radioFemale.setSelected(true);
            //else                                                   radioMale.setSelected(true);
          }
        }
      );
        // postavljamo slusace
        for (java.awt.Component component : getComponents())
        {
            //System.out.println("KOntrola " + component.getName());
            // preskacemo sve komponente koje su null ili nemaju prefiks flg2_ - one nemaju veze sa bazom
            if (component.getName() == null || !component.getName().startsWith("flg2")) continue;
            // ako je kontrola tekst polje, postavljamo da prati promenu sadrzaja teskt polja.
            if (javax.swing.JTextField.class.isInstance(component))
            {
                //System.out.println("Pronadjena: " + component.getName());
                ((javax.swing.JTextField)component).getDocument().addDocumentListener (
                            new javax.swing.event.DocumentListener() {
                            public void insertUpdate(DocumentEvent e) { updated(e);}
                            public void removeUpdate(DocumentEvent e) { updated(e);}
                            public void changedUpdate(DocumentEvent e) { updated(e);}
                            public void updated(DocumentEvent e) {setDataModified(true);}
                            });
            }
            // inace, za ostale kontrole... IntegerField i DateField
            else
            {
                component.addPropertyChangeListener(
                new java.beans.PropertyChangeListener() {
                public void propertyChange(PropertyChangeEvent evt) {
                if (evt.getPropertyName().equals("value"))
                  setDataModified(true);
                }});
            }
        }
        // postavljamo da Table EmployeeInsurance, prati ovaj editor
        try
        {
            Database.getTable("EmployeeInsurance").setDataEditor(this);
        } catch (SQLException ex)
        {
            ex.printStackTrace();
            log("Gem", "EmployeeDataEditor.java", Logger.FATAL_ERROR, i18n("Unable to attach editor to the table."), ex);
        }
        // i postaljamo podatke na "nepromenjene"
        setDataModified(false);
    }


  public void userLoggedIn() {

      checkPrivileges();
  }


  /* see if user has all privileges or disable all elements */
  private void checkPrivileges() {

      // if user doesn't have all access disable all fields
     java.util.LinkedList<java.awt.Container> containers = new java.util.LinkedList();
     containers.add(this);

     while(!containers.isEmpty()) {

       java.awt.Container current = containers.getFirst(); // get first element from list
       containers.removeFirst();                           // now remove it from list, it is not needed anymore

       for (java.awt.Component component: current.getComponents()) {
           if (!Integrator._user.getPrivAllAccess())
               component.setEnabled(false);
           else
               component.setEnabled(true);
       }
     }

      if (!Integrator._user.getPrivAllAccess()) {

        btnModifyInsured.setEnabled(false);
        btnModifyInsured.setVisible(false);

        btnDeleteInsured.setEnabled(false);
        btnDeleteInsured.setVisible(false);

        btnNewInsured.setEnabled(false);
        btnNewInsured.setVisible(false);
      } else {

        btnModifyInsured.setEnabled(true);
        btnModifyInsured.setVisible(true);

        btnDeleteInsured.setEnabled(true);
        btnDeleteInsured.setVisible(true);

        btnNewInsured.setEnabled(true);
        btnNewInsured.setVisible(true);
      }

  }

    public void update() throws SQLException
    {
        // prvo postavljamo naziv zaposlenog, tj. labelu iznad liste.
        lblEmployee.setText
                (
                "<html>(" + Database.getTable("Employee").getResultSet().getString("EmployeeID") + ") " +
                "<b>" + Database.getTable("Employee").getResultSet().getString("EmployeeSurname") + ", " +
                Database.getTable("Employee").getResultSet().getString("EmployeeFirstName") + "</b>"
                );

        _currentEmployee = Database.getTable("Employee").getResultSet().getInt("EmployeeID");
        _currentLBO = Database.getTable("Employee").getResultSet().getString("EmployeeLBO");

        String query = "SELECT ei.EmployeeInsuranceID as keyName, CONCAT(ei.EmployeeInsuranceFirstName, ' ', ei.EmployeeInsuranceSurname) as fieldName FROM " +
                " EmployeeInsurance ei, Employee e WHERE e.EmployeeID = " + _currentEmployee + " AND e.EmployeeID = ei.EmployeeID;";

        listCurrentInsurancies.setQuery(query);
        // zbog promene LBO-a, stavljamo da kontrola prati tabelu employee ili sta??
        listCurrentInsurancies.listenTables("EmployeeInsurance, Employee");
        
        btnDeleteInsured.setEnabled(false);
        btnModifyInsured.setEnabled(false);

        // postavljamo inicijalni sadrzaj kontrola.
        clearGui();
        setDataModified(false);
        //listCurrentInsurancies.clearSelection();
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        flg2_EmployeeInsuranceGenderGroup = new javax.swing.ButtonGroup();
        flg2_EmployeeInsuranceFirstName = new javax.swing.JTextField();
        flg2_EmployeeInsuranceSurname = new javax.swing.JTextField();
        lblFirstName = new javax.swing.JLabel();
        lblSurname = new javax.swing.JLabel();
        btnNewInsured = new javax.swing.JButton();
        btnModifyInsured = new javax.swing.JButton();
        btnDeleteInsured = new javax.swing.JButton();
        lblEmployee = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        listCurrentInsurancies = new org.foment.joliage3.newt.SQLListBox();
        flg2_EmployeeInsuranceJMBG = new javax.swing.JFormattedTextField();
        flg2_EmployeeInsuranceDateOfBirth = new org.foment.joliage3.newt.DateField();
        lblDateOfBirth = new javax.swing.JLabel();
        lblJMBG = new javax.swing.JLabel();
        lblGender = new javax.swing.JLabel();
        radioMale = new javax.swing.JRadioButton();
        radioFemale = new javax.swing.JRadioButton();
        flg2_EmployeeInsuranceGender = new javax.swing.JTextField();
        flg2_EmployeeInsuranceStateOfBirth = new javax.swing.JTextField();
        flg2_EmployeeInsuranceCityOfBirth = new javax.swing.JTextField();
        lblStateOfBirth = new javax.swing.JLabel();
        lblCityOfBirth = new javax.swing.JLabel();

        flg2_EmployeeInsuranceFirstName.setName("flg2_EmployeeInsuranceFirstName"); // NOI18N

        flg2_EmployeeInsuranceSurname.setName("flg2_EmployeeInsuranceSurname"); // NOI18N

        lblFirstName.setText(i18n("First Name"));

        lblSurname.setText(i18n("Surname"));

        btnNewInsured.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/foment/gem/images/employees_button_insert.png"))); // NOI18N
        btnNewInsured.setText(i18n("Insert new insured"));
        btnNewInsured.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNewInsuredActionPerformed(evt);
            }
        });

        btnModifyInsured.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/foment/gem/images/employees_button_update.png"))); // NOI18N
        btnModifyInsured.setText(i18n("Modify insured"));
        btnModifyInsured.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnModifyInsuredActionPerformed(evt);
            }
        });

        btnDeleteInsured.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/foment/gem/images/employees_button_reset.png"))); // NOI18N
        btnDeleteInsured.setText(i18n("Remove insured"));
        btnDeleteInsured.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteInsuredActionPerformed(evt);
            }
        });

        lblEmployee.setText("jLabel1");

        listCurrentInsurancies.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                listCurrentInsuranciesValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(listCurrentInsurancies);

        flg2_EmployeeInsuranceJMBG.setFormatterFactory(new javax.swing.JFormattedTextField.AbstractFormatterFactory() {
            public javax.swing.JFormattedTextField.AbstractFormatter getFormatter(javax.swing.JFormattedTextField tf) {
                try {
                    javax.swing.text.MaskFormatter mask = new javax.swing.text.MaskFormatter("#############");
                    //mask.setPlaceholder("0000000000000");
                    mask.setPlaceholderCharacter('0');
                    return mask;
                } catch (java.text.ParseException ex) {
                    ex.printStackTrace();
                }
                return null;
            }
        });
        flg2_EmployeeInsuranceJMBG.setMinimumSize(new java.awt.Dimension(100, 19));
        flg2_EmployeeInsuranceJMBG.setName("flg2_EmployeeInsuranceJMBG"); // NOI18N

        flg2_EmployeeInsuranceDateOfBirth.setName("flg2_EmployeeInsuranceDateOfBirth"); // NOI18N

        lblDateOfBirth.setText(i18n("Date of Birth"));

        lblJMBG.setText(i18n("JMBG"));

        lblGender.setText(i18n("Gender"));

        flg2_EmployeeInsuranceGenderGroup.add(radioMale);
        radioMale.setText(i18n("Male"));
        radioMale.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
        radioMale.setMargin(new java.awt.Insets(0, 0, 0, 0));
        radioMale.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                radioMaleItemStateChanged(evt);
            }
        });

        flg2_EmployeeInsuranceGenderGroup.add(radioFemale);
        radioFemale.setText(i18n("Female"));
        radioFemale.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
        radioFemale.setMargin(new java.awt.Insets(0, 0, 0, 0));
        radioFemale.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                radioFemaleItemStateChanged(evt);
            }
        });

        flg2_EmployeeInsuranceGender.setEditable(false);
        flg2_EmployeeInsuranceGender.setName("flg2_EmployeeInsuranceGender"); // NOI18N
        flg2_EmployeeInsuranceGender.setVisible(false);

        flg2_EmployeeInsuranceStateOfBirth.setName("flg2_EmployeeInsuranceStateOfBirth"); // NOI18N

        flg2_EmployeeInsuranceCityOfBirth.setName("flg2_EmployeeInsuranceCityOfBirth"); // NOI18N

        lblStateOfBirth.setText(i18n("State"));
        lblStateOfBirth.setMaximumSize(new java.awt.Dimension(100, 15));
        lblStateOfBirth.setMinimumSize(new java.awt.Dimension(100, 15));

        lblCityOfBirth.setText(i18n("City"));
        lblCityOfBirth.setMaximumSize(new java.awt.Dimension(100, 15));
        lblCityOfBirth.setMinimumSize(new java.awt.Dimension(100, 15));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(36, 36, 36)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblEmployee, javax.swing.GroupLayout.DEFAULT_SIZE, 626, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnNewInsured, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(27, 27, 27)
                        .addComponent(btnModifyInsured, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 45, Short.MAX_VALUE)
                        .addComponent(btnDeleteInsured, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 201, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblStateOfBirth, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblGender)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(lblCityOfBirth, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(lblSurname, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(lblFirstName, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(lblDateOfBirth, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(lblJMBG, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 86, Short.MAX_VALUE)))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(radioMale)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(radioFemale)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(flg2_EmployeeInsuranceGender, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(12, 12, 12)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(flg2_EmployeeInsuranceCityOfBirth, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 303, Short.MAX_VALUE)
                                    .addComponent(flg2_EmployeeInsuranceStateOfBirth, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 303, Short.MAX_VALUE)
                                    .addComponent(flg2_EmployeeInsuranceJMBG, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 303, Short.MAX_VALUE)
                                    .addComponent(flg2_EmployeeInsuranceDateOfBirth, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 303, Short.MAX_VALUE)
                                    .addComponent(flg2_EmployeeInsuranceFirstName, javax.swing.GroupLayout.DEFAULT_SIZE, 303, Short.MAX_VALUE)
                                    .addComponent(flg2_EmployeeInsuranceSurname, javax.swing.GroupLayout.DEFAULT_SIZE, 303, Short.MAX_VALUE))))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(43, 43, 43)
                .addComponent(lblEmployee)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblFirstName)
                            .addComponent(flg2_EmployeeInsuranceFirstName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblSurname)
                            .addComponent(flg2_EmployeeInsuranceSurname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(flg2_EmployeeInsuranceDateOfBirth, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(flg2_EmployeeInsuranceStateOfBirth, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(lblStateOfBirth, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(flg2_EmployeeInsuranceCityOfBirth, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(lblCityOfBirth, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(flg2_EmployeeInsuranceJMBG, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(lblJMBG)))
                            .addComponent(lblDateOfBirth)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(1, 1, 1)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(radioMale)
                        .addComponent(radioFemale)
                        .addComponent(flg2_EmployeeInsuranceGender, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(lblGender))
                .addGap(108, 108, 108)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnNewInsured)
                    .addComponent(btnModifyInsured)
                    .addComponent(btnDeleteInsured))
                .addContainerGap(28, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void listCurrentInsuranciesValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_listCurrentInsuranciesValueChanged
        // TODO add your handling code here:
        // ako smo kliknuli na neku stavku u tabeli, aktiviramo opcije za brisanje i dodavanje.
        btnDeleteInsured.setEnabled(true);
        btnModifyInsured.setEnabled(true);

        // onemogucavamo biranje drugog osiguranika, ako je promenjen neki podatak.
        if (isDataModified())
            return;
        
        // forsiramo da se mouseClicked obradi PRE nego valueChanged, kako bismo
        // imali "najsveziju" vrednostu keyValue.
        listCurrentInsurancies.listener();
        
        // i to na sta smo kliknuli, postavljamo u tekst polja.
        _currentInsured = listCurrentInsurancies.getValue(); // uzimamo redni broj imena.
        //System.out.print("listValueChanged: Changed " + listCurrentInsurancies.getSelectedIndex());
        
        //System.out.println(" SQL getValue() = " + position);
        if (_currentEmployee != -1 && _currentInsured != -1)
        {   
            String query1 = "SELECT * from EmployeeInsurance where EmployeeInsuranceID = " + _currentInsured;

            try
            {
                Connection  conn = Database.getConnection();
                ResultSet rs = Database.getConnection().createStatement().executeQuery(query1);
                if (rs.first())
                {
                    java.util.LinkedList<java.awt.Container> containerList = new java.util.LinkedList();
                    containerList.add(this);

                    while (!containerList.isEmpty())
                    {
                        java.awt.Container current = containerList.getFirst();
                        containerList.removeFirst();

                        for (java.awt.Component component: current.getComponents())
                        {
                            if (component.getName() != null && component.getName().startsWith("flg2_"))
                            {
                                if (IntegerField.class.isInstance(component))
                                {
                                    ((IntegerField)component).setValue(rs.getInt(component.getName().substring(5)));
                                }
                                else if (DateField.class.isInstance(component))
                                {
                                    java.util.Date date;
                                    try
                                    {
                                        date = rs.getDate(component.getName().substring(5));
                                    } catch (Exception ex) { date = null; }
                                    ((DateField)component).setValue(date);
                                }
                                else if (JTextField.class.isInstance(component))
                                {
                                    ((JTextField)component).setText(rs.getString(component.getName().substring(5)));
                                }
                                else if (SQLComboBox.class.isInstance(component))
                                {
                                // to nam ne treba!!
                                //((SQLComboBox)component).setValue(rs.getInt(component.getName().substring(5)));
                                }
                                else
                                {
                                    System.err.println("Unknown component : " + component.getName());
                                }
                            }
                            else
                            {   // ako panel sadrzi mozda jos neki kontejner
                                if (java.awt.Container.class.isInstance(component))
                                containerList.addLast((java.awt.Container)component);
                            }
                        }
                    }
                }
                rs.close();
                conn.close();
            }
            catch(SQLException e) {e.printStackTrace();}

            setDataModified(false);
        }
    }//GEN-LAST:event_listCurrentInsuranciesValueChanged

    private void btnNewInsuredActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNewInsuredActionPerformed
        // TODO add your handling code here:
        if (_currentEmployee != -1)
        {
            String message = i18n("Are you sure you want to add new insured for this Employee?");
            String[] options = {i18n("Yes"), i18n("No")};

            int option = JOptionPane.showOptionDialog(this, message, "Foment Group", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, 0);

            // ako smo kliknuli na YES, uzimamo podatke iz tekst polja...
            if (option == JOptionPane.YES_OPTION)
            {
                try
                {

                    /* izmenjena varijanta, posto je kljuc u bazi sada tipa auto_increment */
                    String query = "INSERT INTO EmployeeInsurance ";

                    String firstName = flg2_EmployeeInsuranceFirstName.getText();
                    String surname   = flg2_EmployeeInsuranceSurname.getText();
                    String gender    = flg2_EmployeeInsuranceGender.getText();
                    String jmbg      = flg2_EmployeeInsuranceJMBG.getText();
                    String city      = flg2_EmployeeInsuranceCityOfBirth.getText();
                    String state     = flg2_EmployeeInsuranceStateOfBirth.getText();
                    String birthDate = flg2_EmployeeInsuranceDateOfBirth.getFormattedValue();
                    String lbo       = ((_currentLBO == null) ? "" : _currentLBO);


                    query += "(EmployeeInsuranceFirstName, EmployeeInsuranceSurname, EmployeeInsuranceGender," +
                        "EmployeeInsuranceJMBG, EmployeeInsuranceCityOfBirth, EmployeeInsuranceStateOfBirth, " +
                        "EmployeeInsuranceDateOfBirth, EmployeeID, EmployeeLBO)";

                    query += " VALUES ";
                    query += "('" + firstName + "', '" + surname + "', '" + gender + "', '" + jmbg + "', " +
                        "'" + city + "', '" + state + "', '" + birthDate + "', "+ _currentEmployee +", '" + lbo +"');";

                    Connection  conn = Database.getConnection();
                    conn.createStatement().executeUpdate(query);
                    conn.close();

/*
                    ResultSet rs = Database.getConnection().createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                        ResultSet.CONCUR_UPDATABLE).executeQuery("SELECT max(EmployeeInsuranceID) + 1 as InsertID FROM EmployeeInsurance");
                    int InsertID = 0;
                    if (rs.first())
                        InsertID = rs.getInt("InsertID");
                    rs = Database.getConnection().createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                        ResultSet.CONCUR_UPDATABLE).executeQuery("SELECT * FROM EmployeeInsurance");
                    // pomeramo se na prazan red, za unos novog osiguranika
                    rs.moveToInsertRow();
                    // i rucno unosimo kljuc, jer on nije sadrzan u gui-ju
                    rs.updateInt("EmployeeInsuranceID", InsertID);
                    rs.updateInt("EmployeeID", _currentEmployee);
                    java.util.LinkedList<java.awt.Container> containerList = new java.util.LinkedList();
                    containerList.add(this);

                    while (!containerList.isEmpty())
                    {
                        java.awt.Container current = containerList.getFirst();
                        containerList.removeFirst();

                        for (java.awt.Component component: current.getComponents())
                        {
                            if (component.getName() != null && component.getName().startsWith("flg2_"))
                            {
                                if (IntegerField.class.isInstance(component))
                                    { rs.updateInt(component.getName().substring(5), ((IntegerField)component).getValue()); }
                                else if (DateField.class.isInstance(component))
                                {
                                    java.util.Date date = ((DateField)component).getValue();
                                    rs.updateDate(component.getName().substring(5),(date == null)?null:new java.sql.Date(date.getTime()));
                                }
                                else if (JTextField.class.isInstance(component))
                                { rs.updateString(component.getName().substring(5), ((JTextField)component).getText());}

                                else if (SQLComboBox.class.isInstance(component))
                                {
                                // to nam ne treba!!
                                //((SQLComboBox)component).setValue(rs.getInt(component.getName().substring(5)));
                                }
                                else { System.err.println("Unknown component : " + component.getName()); }
                            }

                            else
                            {   // ako panel sadrzi mozda jos neki kontejner
                                if (java.awt.Container.class.isInstance(component))
                                    containerList.addLast((java.awt.Container)component);
                            }
                        }
                    }
                    rs.insertRow();

                    */

                    clearGui();
                    setDataModified(false);
                    listCurrentInsurancies.refresh();
                }
                catch(SQLException ex)
                {log("Gem", "EmployeeInsuranceEditor.java", Logger.ERROR, i18n("Unable to insert data"), ex);
                ex.printStackTrace();}
            }
            
        }
    }//GEN-LAST:event_btnNewInsuredActionPerformed

    private void btnModifyInsuredActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnModifyInsuredActionPerformed
        // TODO add your handling code here:

        String query1 = "SELECT * from EmployeeInsurance where EmployeeInsuranceID = " + _currentInsured;
        try
        {
            Connection  conn = Database.getConnection();
            ResultSet rs = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
            ResultSet.CONCUR_UPDATABLE).executeQuery(query1);
            if (rs.first())
            {
                java.util.LinkedList<java.awt.Container> containerList = new java.util.LinkedList();
                containerList.add(this);

                while (!containerList.isEmpty())
                {
                    java.awt.Container current = containerList.getFirst();
                    containerList.removeFirst();

                    for (java.awt.Component component: current.getComponents())
                    {
                        if (component.getName() != null && component.getName().startsWith("flg2_"))
                        {
                            if (IntegerField.class.isInstance(component))
                            { rs.updateInt(component.getName().substring(5), ((IntegerField)component).getValue()); }
                            else if (DateField.class.isInstance(component))
                            {
                                java.util.Date date = ((DateField)component).getValue();
                                rs.updateDate(component.getName().substring(5),(date == null)?null:new java.sql.Date(date.getTime()));
                            }
                            else if (JTextField.class.isInstance(component))
                            { rs.updateString(component.getName().substring(5), ((JTextField)component).getText());}
                            
                            else if (SQLComboBox.class.isInstance(component))
                            {
                                // to nam ne treba!!
                                //((SQLComboBox)component).setValue(rs.getInt(component.getName().substring(5)));
                            }
                            else { System.err.println("Unknown component : " + component.getName()); }
                        }
                        else
                        {   // ako panel sadrzi mozda jos neki kontejner
                            if (java.awt.Container.class.isInstance(component))
                                containerList.addLast((java.awt.Container)component);
                        }
                    }
                }
            }
            rs.updateRow();
            rs.close();
            conn.close();
            Database.getTable("EmployeeInsurance").reload();
            setDataModified(false);
        }
        catch (SQLException e) {e.printStackTrace();}
    }//GEN-LAST:event_btnModifyInsuredActionPerformed

    private void btnDeleteInsuredActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteInsuredActionPerformed
        // TODO add your handling code here:
        // uklanjamo osiguranika.
        String message = i18n("Are you sure you want to delete insured for this Employee?");
        String[] options = {i18n("Yes"), i18n("No")};

        int option = jOptionPane.showOptionDialog(this, message, "Foment Group", jOptionPane.YES_NO_OPTION, jOptionPane.QUESTION_MESSAGE, null, options, 0);

        if (option == jOptionPane.YES_OPTION)
        {
            String query = "DELETE FROM EmployeeInsurance WHERE EmployeeInsuranceID = " +
            _currentInsured + ";";

            try
            {
                Connection  conn = Database.getConnection();
                conn.createStatement().executeUpdate(query);
                conn.close();
                Database.getTable("EmployeeInsurance").reload();
            }catch (SQLException ex) { ex.printStackTrace(); }
        }
        listCurrentInsurancies.refresh();
        setEditing(false);
        clearGui();
        setDataModified(false);

    }//GEN-LAST:event_btnDeleteInsuredActionPerformed

    private void radioMaleItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_radioMaleItemStateChanged
        if (evt.getStateChange() == evt.SELECTED)
            if (!flg2_EmployeeInsuranceGender.getText().equals("m")) {
                flg2_EmployeeInsuranceGender.setText("m");
                setDataModified(true);
            }
}//GEN-LAST:event_radioMaleItemStateChanged

    private void radioFemaleItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_radioFemaleItemStateChanged
        if (evt.getStateChange() == evt.SELECTED)
            if (!flg2_EmployeeInsuranceGender.getText().equals("f")) {
                flg2_EmployeeInsuranceGender.setText("f");
                setDataModified(true);
            }
}//GEN-LAST:event_radioFemaleItemStateChanged

    public void activateEditor() {
    setDataModified(false);
    setEditing(true);
  }

  public void setEditing(boolean editing) {
    btnDeleteInsured.setEnabled(editing);
    btnModifyInsured.setEnabled(editing);
    //btnNewInsured.setEnabled(editing);
  }

  public void rowUpdated() {
    setDataModified(false);
  }

  public void rowInserted() {
    setDataModified(false);
  }
  public void setDataModified(boolean modified) { _modified = modified;}
  public boolean isDataModified() { return _modified; }

  
 
  private void clearGui()
  {
      java.util.LinkedList<java.awt.Container> containers = new java.util.LinkedList();
      containers.add(this);
      // prazni kontrole, kako bi korisnik mogao da unese
      while(!containers.isEmpty()) {

         java.awt.Container current = containers.getFirst(); // get first element from list
         containers.removeFirst();                           // now remove it from list, it is not needed anymore

         for (java.awt.Component component: current.getComponents()) {
             if (component.getName() != null && component.getName().startsWith("flg2_")) {
              if (IntegerField.class.isInstance(component)) {
                ((IntegerField)component).setValue(0);

              } else if (DateField.class.isInstance(component)) {
                java.util.Date date;
                date = null;
                ((DateField)component).setValue(date);

              } else if (JTextField.class.isInstance(component)) {
                ((JTextField)component).setText("");
              } else if (SQLComboBox.class.isInstance(component)) {
                ((SQLComboBox)component).setValue(0);
              } else if (JRadioButton.class.isInstance(component)) {
                  ((JRadioButton)component).setSelected(false);
              }
              else {
                System.err.println("Unknown component : " + component.getName());
              }
            }
         }
      }
  }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnDeleteInsured;
    private javax.swing.JButton btnModifyInsured;
    private javax.swing.JButton btnNewInsured;
    private javax.swing.JTextField flg2_EmployeeInsuranceCityOfBirth;
    private org.foment.joliage3.newt.DateField flg2_EmployeeInsuranceDateOfBirth;
    private javax.swing.JTextField flg2_EmployeeInsuranceFirstName;
    private javax.swing.JTextField flg2_EmployeeInsuranceGender;
    private javax.swing.ButtonGroup flg2_EmployeeInsuranceGenderGroup;
    private javax.swing.JFormattedTextField flg2_EmployeeInsuranceJMBG;
    private javax.swing.JTextField flg2_EmployeeInsuranceStateOfBirth;
    private javax.swing.JTextField flg2_EmployeeInsuranceSurname;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblCityOfBirth;
    private javax.swing.JLabel lblDateOfBirth;
    private javax.swing.JLabel lblEmployee;
    private javax.swing.JLabel lblFirstName;
    private javax.swing.JLabel lblGender;
    private javax.swing.JLabel lblJMBG;
    private javax.swing.JLabel lblStateOfBirth;
    private javax.swing.JLabel lblSurname;
    private org.foment.joliage3.newt.SQLListBox listCurrentInsurancies;
    private javax.swing.JRadioButton radioFemale;
    private javax.swing.JRadioButton radioMale;
    // End of variables declaration//GEN-END:variables

    private int _currentEmployee = -1; // trenutno izabrani zaposleni, tj. njegov ID
    private JOptionPane jOptionPane;
    private boolean _modified; // indikator da li su podaci promenjeni
    private int _currentInsured = -1;
    String _currentLBO;
}
